﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Rung.Net.Base
{
    /// <summary>
    /// 客户端实体。
    /// </summary>
    public class ClientItem<T> : IDisposable
    {
        /// <summary>
        /// 客户端在服务端注册的唯一标识。
        /// </summary>
        public Guid Id;

        /// <summary>
        /// 客户端在客户端注册的名称（由客户端定义）。
        /// </summary>
        public string Name = "NULL";

        /// <summary>
        /// 最近一次收到客户端消息的时间。
        /// </summary>
        public DateTime LastInteractionTime;

        public NetBaseStream<T> Stream;

        public ClientItem(Guid id, DateTime last, NetBaseStream<T> stream)
        {
            this.Id = id;
            this.LastInteractionTime = last;
            this.Stream = stream;
        }

        public void Send(T data)
        {
            this.Stream.Send(data);
        }

        public void Stop()
        {
            if (this.Stream != null)
                this.Stream.Stop();
        }

        public override string ToString()
        {
            return this.Name;
        }

        public void Dispose()
        {
            this.Stop();
        }
    }

    public class ClientItemCollection<T> : Dictionary<Guid, ClientItem<T>>
    {
        private object OBJ_read = new object();
        private object OBJ_write = new object();

        public new void Add(Guid id, ClientItem<T> client)
        {
            lock (OBJ_write)
            {
                base.Add(id, client);
            }
        }

        public new void Remove(Guid id)
        {
            lock (OBJ_write)
            {
                base.Remove(id);
            }
        }

        public new void Clear()
        {
            lock (OBJ_write)
            {
                base.Clear();
            }
        }
    }
}
